<?php
/**
 * @name BaseController
 * @author ruansheng
 * @desc 基础控制器
 */
class Base extends Yaf_Controller_Abstract {

    protected $_id = null;
    protected $info = null;

    private $whiteUri = array(
        '/login/index',
        '/login/execLogin',
        '/login/addStudent'  //测试使用
    );

    public function init() {
        session_start();
        $requestUri = $_SERVER['REQUEST_URI'];
        if(!in_array($requestUri, $this->whiteUri)) {
            // 获取session
            $_id = $_SESSION['_id'];
            if(empty($_id)) {
                $this->redirect();
            }

            $role = $_SESSION['role'];

            if(empty($role)) {
                $this->redirect();
            }

            switch($role) {
                case 1:
                    $Student = new StudentModel();
                    $info = $Student->getStudentInfo($_id);
                    break;
                case 2:
                    $Teacher = new TeacherModel();
                    $info = $Teacher->getTeacherInfo($_id);
                    break;
                case 3:
                    $Manager = new ManagerModel();
                    $info = $Manager->getManagerInfo($_id);
                    break;
                default:
                    $this->redirect();
                    break;
            }

            $this->_id = $_id;
            $this->info = $info;
            $this->getView()->assign('_id', $_id);
            $this->getView()->assign('info', $info);
            $this->getView()->assign('role', $role);
        } else {
            $_id = $_SESSION['_id'];
            if(!empty($_id)) {
                $this->redirect('/index/index');
            }
        }
    }

    /**
     * 返回json
     * @param int    $en
     * @param string $em
     * @param array  $data
     */
    public function responseJson($en = 200, $em = 'ok', $data = []) {
        header('Content-type:text/json;');
        $ret = array(
            'en' => $en,
            'em' => $em,
            'data' => $data
        );
        exit(json_encode($ret));
    }

    /**
     * 页面跳转
     * @param string $uri
     */
    public function redirect($uri = '/login/index') {
        header('Location:'.$uri);
        exit;
    }

    /**
     * 打印输出
     * @param      $var
     * @param bool $exit
     */
    public function dump($var,$exit = false){
        echo '<pre>';
            print_r($var);
        echo '</pre>';
        if($exit) {
            exit;
        }
    }
}
